﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Data;
using System.Web.Mvc;
using System.Text;
using System.EnterpriseServices;
using Webdiyer.WebControls.Mvc;
using YiYiTong.Rocket.Business;
using YiYiTong.Rocket.Entity;
using YiYiTong.Rocket.Model.Manager;
using YiYiTong.Rocket.Helper;
using YiYiTong.Rocket.Model.ParamModel;
using YiYiTong.Rocket.EFDBFirst;
using System.Web;
using System.IO;
using System.Text.RegularExpressions;
using YiYiTong.Rocket.Model;

namespace YiYiTong.Rocket.ManageWeb.Controllers
{
    public class OrderPlaceController : BaseController
    {
        #region 获取列表
        [Description("预热报价列表")]
        [ViewPage]
        public ActionResult OrderPlaceList(OrderPlaceQueryModel queryModel)
        {
            queryModel.Trim();
            ViewBag.Title = "预热报价列表";
            ViewBag.paramModel = queryModel;
            ADZ_MasterEntities dbcontext = new ADZ_MasterEntities();

            var queryable = dbcontext.View_OrderPlace.Where(t => 0 == 0);

            if (!string.IsNullOrWhiteSpace(queryModel.account_mobile))
                queryable = queryable.Where(t => t.account_mobile.StartsWith(queryModel.account_mobile));

            if (queryModel.goods_id.HasValue && queryModel.goods_id > 0)
                queryable = queryable.Where(t => t.goods_id == queryModel.goods_id);

            if (!string.IsNullOrWhiteSpace(queryModel.MPN))
                queryable = queryable.Where(t => t.MPN.StartsWith(queryModel.MPN));

            if (queryModel.place_status != -10)
                queryable = queryable.Where(t => t.place_status == queryModel.place_status);

            if (queryModel.is_del != -10)
                queryable = queryable.Where(t => t.is_del == queryModel.is_del);

            if (queryModel.is_succ != -10)
                queryable = queryable.Where(t => t.is_succ == queryModel.is_succ);

            if (queryModel.update_time_begin.HasValue)
                queryable = queryable.Where(t => t.update_time >= queryModel.update_time_begin);
            if (queryModel.update_time_end.HasValue)
            {
                var endTime = queryModel.update_time_end.Value.AddSeconds(1);
                queryable = queryable.Where(t => t.update_time < endTime);
            }


            if (queryModel.pay_succ_time_begin.HasValue)
                queryable = queryable.Where(t => t.pay_succ_time >= queryModel.pay_succ_time_begin);
            if (queryModel.pay_succ_time_end.HasValue)
            {
                var endTime = queryModel.pay_succ_time_end.Value.AddSeconds(1);
                queryable = queryable.Where(t => t.pay_succ_time < endTime);
            }

            if (queryModel.end_time_begin.HasValue)
                queryable = queryable.Where(t => t.end_time >= queryModel.end_time_begin);
            if (queryModel.end_time_end.HasValue)
            {
                var endTime = queryModel.end_time_end.Value.AddSeconds(1);
                queryable = queryable.Where(t => t.end_time < endTime);
            }


            int rowcounts = queryable.Count();

            ViewData["AllCount"] = rowcounts;

            var querylist = queryable.OrderByDescending(t => t.goods_id).ThenByDescending(t => t.uid).ThenByDescending(t => t.update_time)
                .Skip(queryModel.pageSize * (queryModel.pageIndex - 1))
                .Take(queryModel.pageSize)
                .ToList();


            PagedList<View_OrderPlace> pagedlist = null;
            if (querylist != null && querylist.Count != 0)
                pagedlist = new PagedList<View_OrderPlace>(querylist, queryModel.pageIndex, queryModel.pageSize, rowcounts);
            return View(pagedlist);
        }

        [Description("预热出价详情")]
        [ViewPage]
        public ActionResult OrderPlaceInfo(long id = 0)
        {
            ADZ_MasterEntities dbcontext = new ADZ_MasterEntities();
            OrderPlaceModel paramModel = new OrderPlaceModel();
            ViewBag.Title = "预热出价详情";
            if (id > 0)
            {
                paramModel.view_OrderPlace = dbcontext.View_OrderPlace.FirstOrDefault(t => t.seq_id == id);
                if (paramModel.view_OrderPlace != null)
                {
                    paramModel.views_Goods = dbcontext.Views_Goods.FirstOrDefault(t => t.goods_id == paramModel.view_OrderPlace.goods_id);

                    if (paramModel.view_OrderPlace.order_master_id > 0)
                        paramModel.view_Order = dbcontext.View_Order.FirstOrDefault(t => t.order_id == paramModel.view_OrderPlace.order_master_id);
                }
            }

            return View(paramModel);
        }



        [Description("设置中标")]
        [HttpPost]
        public ActionResult setHit(long id)
        {
            ADZ_MasterEntities dbcontext = new ADZ_MasterEntities();

            ResponseMsg resMsg = new ResponseMsg();
            resMsg.IsSuccess = false;
            resMsg.Message = "操作失败";

            var order_place = dbcontext.ADZ_GoodsPlace.FirstOrDefault(t => t.seq_id == id);
            if (order_place != null)
            {
                if (order_place.is_hit == 1)
                {
                    resMsg.IsSuccess = true;
                    resMsg.Message = "已设置中标";
                    return Json(resMsg, JsonRequestBehavior.AllowGet);
                }
                order_place.hit_time = DateTime.Now;
                order_place.is_hit = 1;

                dbcontext.SaveChanges();
                resMsg.IsSuccess = true;
                resMsg.Message = "操作成功";
            }

            return Json(resMsg, JsonRequestBehavior.AllowGet);
        }

        [Description("设置中标并下单")]
        [HttpPost]
        public ActionResult setHitOrder(OrderPlaceHitOrderModel model)
        {
            ADZ_MasterEntities dbcontext = new ADZ_MasterEntities();

            ResponseMsg resMsg = new ResponseMsg();
            resMsg.IsSuccess = false;
            resMsg.Message = "操作失败";

            long uid = model.uid;
            //添加新地址
            if (model.checkaddress == 0)
            {
                string checkresult = model.newCreateAddress.CheckParam();
                if (!string.IsNullOrWhiteSpace(checkresult))
                {
                    resMsg.Message = checkresult;
                    return Json(resMsg, JsonRequestBehavior.AllowGet);
                }
                string cityid = model.newCreateAddress.new_city_id.Trim();
                string cityname = model.newCreateAddress.new_city_name.Trim();
                string address = model.newCreateAddress.new_address.Trim();
                string receiver = model.newCreateAddress.new_receiver.Trim();
                string telephone = model.newCreateAddress.new_receiver_telephone.Trim();
                int isDefault = 0;
                var addresult = AccountBiz.Instance.AddAddress(uid, cityid, cityname, address, receiver, telephone, isDefault);
                if (addresult.Item1)
                {
                    model.checkaddress = addresult.Item2;
                }
                else
                {
                    resMsg.Message = $"地址信息保存出错，{addresult.Item3}";
                    return Json(resMsg, JsonRequestBehavior.AllowGet);
                }
            }
            //开始创建订单
            var view_OrderPlace = dbcontext.View_OrderPlace.FirstOrDefault(t => t.seq_id == model.seq_id);
            if (view_OrderPlace != null)
            {
                var order_place = dbcontext.ADZ_GoodsPlace.FirstOrDefault(t => t.seq_id == model.seq_id);
                if (order_place != null)
                {
                    if (order_place.is_hit != 1)
                    {
                        order_place.hit_time = DateTime.Now;
                        order_place.is_hit = 1;
                        order_place.place_price = model.place_price;//20190217单价修改掉
                        dbcontext.SaveChanges();


                        ////设置其他预定为取消
                        //var ls = dbcontext.ADZ_GoodsPlace.Where(t => t.goods_id == order_place.goods_id
                        //&& t.is_hit != 1
                        //&& t.place_status.Value == (byte)PlaceStatus.Placeing);
                        //ls.ToList().ForEach(t =>
                        //{
                        //    t.is_del = 1;
                        //    t.update_time = DateTime.Now;
                        //    t.place_status = (byte)PlaceStatus.Cancel;
                        //});
                        //dbcontext.SaveChanges();
                    }
                }

                List<OrderYureDetailReq> goodlist = new List<OrderYureDetailReq>();
                goodlist.Add(new OrderYureDetailReq
                {
                    goods_id = view_OrderPlace.goods_id.Value,
                    place_amount = view_OrderPlace.goods_amount.Value,
                    place_price = model.place_price
                });
                int pay_type = 1;
                var goods_info = dbcontext.ADZ_GoodsMaster.FirstOrDefault(t => t.goods_id == view_OrderPlace.goods_id.Value);
                if(goods_info != null && goods_info.include_tax == 1)
                {
                    pay_type = 0;
                }
                CreateYureOrderReq createOrderReq = new CreateYureOrderReq
                {
                    addressid = model.checkaddress,
                    invoice_id = 0,
                    pay_type = pay_type,
                    remark = model.remark,
                    total_money = view_OrderPlace.goods_amount.Value * model.place_price,
                    goodlist = goodlist
                };
                var createResult = OrderBiz.Instance.CreateYureOrder(uid, (int)OrderSource.SystenCreate, model.seq_id, createOrderReq);
                if (createResult.Item1)
                {
                    order_place = dbcontext.ADZ_GoodsPlace.FirstOrDefault(t => t.seq_id == model.seq_id);
                    order_place.place_status = (byte)PlaceStatus.WaitPay;
                    order_place.update_time = DateTime.Now;
                    dbcontext.SaveChanges();

                    //商品下架，如果此商品库存不足，自动下架
                    var entity = dbcontext.ADZ_GoodsMaster.FirstOrDefault(t => t.goods_id == order_place.goods_id);
                    if (entity != null && entity.stock_amount < entity.min_amount)
                    {
                        entity.is_withdraw = 1;
                        entity.with_down_time = DateTime.Now;
                        dbcontext.SaveChanges();

                        //设置其他预定为取消
                        var ls = dbcontext.ADZ_GoodsPlace.Where(t => t.goods_id == order_place.goods_id
                        && t.is_hit != 1
                        && t.place_status.Value == (byte)PlaceStatus.Placeing);
                        ls.ToList().ForEach(t =>
                        {
                            t.is_del = 1;
                            t.update_time = DateTime.Now;
                            t.place_status = (byte)PlaceStatus.Cancel;
                        });
                        dbcontext.SaveChanges();

                    }

                    //发送推送消息
                    AddPushMsgModel paramModel = new AddPushMsgModel
                    {
                        aDZ_Pushmessage = new ADZ_Pushmessage
                        {
                            MsgType = 2,
                            ReceiveType = 1,
                            MsgTitle = "预定成功",
                            MsgText = $"您预定出价的商品料号{entity.MPN}已下单成功，订单号为：{createResult.Item3}，请尽快进行支付吧。"
                        },
                        ReceiveUids = model.uid.ToString()
                    };
                    PushMsgBiz.Instance.AddPushMsg(paramModel);

                    var resdata = JsonHelper.Deserialize<Dictionary<string, object>>(createResult.Item2);
                    object order_id;
                    resdata.TryGetValue("order_id", out order_id);
                    OrderBiz.Instance.WriteOrderLog(new ADZ_OrderMasterLog
                    {
                        order_id = ConvertHelper.ConvertTo<long>(order_id, 0),
                        opmsg = "预定下单成功-管理后台",
                        op_user = new CurrentUser().user.loginName
                    });

                    resMsg.IsSuccess = true;
                    resMsg.Message = "操作成功";
                    return Json(resMsg, JsonRequestBehavior.AllowGet);
                }
                else
                {
                    resMsg.Message = createResult.Item3;
                    return Json(resMsg, JsonRequestBehavior.AllowGet);

                }
            }

            return Json(resMsg, JsonRequestBehavior.AllowGet);
        }
        #endregion

    }
}